# -*- coding: utf-8 -*-
#
# Copyright © 2009 Benedikt Eger
#
# This file is part of top-news-buzz.
#
# top-news-buzz is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# top-news-buzz is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with top-news-buzz.  If not, see <http://www.gnu.org/licenses/>.

import re
import logging

from datetime import date, timedelta

from HTMLParser import HTMLParser

from google.appengine.ext import webapp
from google.appengine.ext import db

from topnewsbuzz.config import Config

class DateHelper:
    
    DATE_TYPE_LAST_N_DAYS = 0
    DATE_TYPE_DAY = 1
    DATE_TYPE_MONTH = 2
    DATE_TYPE_YEAR = 3
    DATE_TYPE_WEEK = 4
            
    def __init__(self, year = None, month = None, day = None, week = None):        
        self.current_date = date.today()
        self.current_year = self.current_date.year
        self.current_month = self.current_date.month
        self.current_day = self.current_date.day
        
        if year is None and month is None and day is None:
            self.date_type = DateHelper.DATE_TYPE_LAST_N_DAYS
        elif month is None:
            if week is None:
                self.date_type = DateHelper.DATE_TYPE_YEAR
            else:
                self.date_type = DateHelper.DATE_TYPE_WEEK
        elif day is None:
            self.date_type = DateHelper.DATE_TYPE_MONTH
        else:
            self.date_type = DateHelper.DATE_TYPE_DAY
            
        self.selected_year = year
        self.selected_month = month
        self.selected_day = day
        self.selected_week = week


class UrlHelper:
    
    def __init__(self, request):
        self.date = date.today()
        self.request = request
        
    def path(self):
        return self.request.path
    
    def page_agnostic_path(self):
        path = self.path()
        if path.find('/page') != -1:
            path = path[0:path.find('/page')]
            if path == '':
                path = '/' 
            return path            
        else:
            return self.request.path                    

    def today_url(self):
        return '/%i/%i/%i' % (self.date.year, self.date.month, self.date.day)
    
    def yesterday_url(self):
        yesterday_date = self.date - timedelta(days=1)
        return '/%i/%i/%i' % (yesterday_date.year, yesterday_date.month, yesterday_date.day)
    
    def this_week_url(self):
        return '/%i/week/%i' % (self.date.isocalendar()[0], self.date.isocalendar()[1])
    
    def last_week_url(self):
        last_week_date = self.date - timedelta(days=7)
        return '/%i/week/%i' % (last_week_date.isocalendar()[0], last_week_date.isocalendar()[1])
    
    def this_month_url(self):
        return '/%i/%i' % (self.date.year, self.date.month)
    
    def last_month_url(self):
        last_month_date = self.date - timedelta(days=self.date.day)
        return '/%i/%i' % (last_month_date.year, last_month_date.month)
    
    def this_year_url(self):
        return '/%i' % self.date.year
        
    def set_page(self, page):
        self.page = page
        
    def previous_page_url(self):
        if self.page > 1:
            path = self.request.path if (self.request.path != '/') else ''
            if path.find('/page') != -1:
                path = path[0:path.find('/page')]
            return '%s/page/%i' % (path, self.page - 1)
    
    def next_page_url(self):
        path = self.request.path if (self.request.path != '/') else ''
        if path.find('/page') != -1:
            path = path[0:path.find('/page')]
        return '%s/page/%i' % (path, self.page + 1)    
        
class HTMLStripper(HTMLParser):
    
    def __init__(self):
        self.reset()
        self.fed = []
        
    def handle_data(self, d):
        self.fed.append(d)
        
    def get_data(self):
        text = ' '.join(self.fed)        
        return re.sub(r'\s\s+', ' ', text) 
        
class DatastoreCleanupService(webapp.RequestHandler):

    QUERY_STRING = 'SELECT * FROM NewsArticle WHERE score <= :score_limit ORDER BY score DESC'
    QUERY_FETCH_LIMIT = 250

    def get(self):
        logging.debug('Searching news articles with a score of %.2f or less.' % Config.cleanup_score_limit())
        delete_list = []
        query = db.GqlQuery(DatastoreCleanupService.QUERY_STRING, score_limit = Config.cleanup_score_limit())
        news_list = query.fetch(DatastoreCleanupService.QUERY_FETCH_LIMIT)
        for news_item in news_list:
            if news_item.score_date is not None:                    
                delete_list.append(news_item)            

        for news_item in delete_list:
            logging.debug('Deleting news article "%s".' % news_item.title)
            news_item.delete()
            
        if(len(delete_list) > 0):
            logging.info('Deleted %i news articles matching the cleanup-criteria.' % len(delete_list))
        else:
            logging.debug('Currently no cleanup necessary.')